//
//  XSJTool.m
//  XV
//
//  Created by apple on 2019/03/11.
//  Copyright © 2019 XV. All rights reserved.
//

#import "XSJTool.h"
#import "SDWebImage.h"
#import <DateTools.h>


@implementation XSJTool


/**
 是否为审核状态
 
 @return <#return value description#>
 */
+(BOOL)isReviewStatus
{
    // 解档
//    NSData *userInfoData = [[NSUserDefaults standardUserDefaults] objectForKey:kXRUserInfo];
//    XRUserInfo *userInfo = [NSKeyedUnarchiver unarchiveObjectWithData:userInfoData];
//    if ( userInfo.i_teminal.intValue==1 )
//    {
//        return YES;
//    }
    
    return NO;
}


//内测
+(BOOL)isTFStatus
{
    return NO;
}

//企业
+(BOOL)isEnterpriseStatus
{
    return NO;
}


//获取app_name
+(NSString*)getModel_app_name
{
    return @"xsj_main";
}


//得到软件版本
+(NSString*)getSoftVersion
{
    NSString* str = nil;
    NSString* version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    
#ifdef XiuRen_APP_TEST
    NSString* build = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];
    str = [NSString stringWithFormat:@"V%@ build%@",version,build];
#else
    str = [NSString stringWithFormat:@"V%@",version];
#endif
    
    return str;
}

//得到显示软件版本最终字符串
+(NSString*)getSoftVersionString
{
    NSString* version = [XSJTool getSoftVersion];    
    return version;
}

/**
 *  是否是邮箱
 *
 *  @param email email description
 *
 *  @return <#return value description#>
 */
+ (BOOL) isEmail:(NSString *)email
{
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    
    return [emailTest evaluateWithObject:email];
}

/**
 *  手机号码判断
 *
 *  @return <#return value description#>
 */
+ (BOOL) isPhoneNumber:(NSString *)PhoneNumber
{
    if (kStringIsEmpty(PhoneNumber))
    {
        return NO;
    }
    
    //中国手机号(宽松), 只要是13,14,15,16,17,18,19开头即可
    NSString *phoneRegex = @"^(?:(?:\\+|00)86)?1[3-9]\\d{9}$";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    return [phoneTest evaluateWithObject:PhoneNumber];
}

/**
 *  将一个带有分隔符的字符串拆分成数组
 *
 *  @param strData     带有分隔符的字符串
 *  @param strSeparator     分隔符
 *  @return NSMutableArray 拆分后的数组
 */
+(NSMutableArray *)strToArr: (NSString*)strData Separator:(NSString*)strSeparator
{
    NSMutableArray * arr = [[NSMutableArray alloc]initWithArray:[strData componentsSeparatedByString:strSeparator]];
    
    return arr;
}

/**
 *  将一个数组拆分组成带有分隔符的字符串
 *
 *  @param NSMutableArray 拆分的数组
 *  @param strSeparator     分隔符
 *  @return strData     带有分隔符的字符串
 */
+(NSString *)ArrTostr: (NSMutableArray*)arrData Separator:(NSString*)strSeparator
{
    NSString *str = nil;
    if (arrData==nil)
    {
        return str;
    }
    
    str = [arrData componentsJoinedByString:strSeparator];
    return str;
}


//时间戳转日期
+ (NSDate*)UnixTimeToDate:(long long)lTime
{
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:lTime];
    return date;
}

//得到要显示的时间文本
+(NSString*)timeText:(NSString*)dateline
{
    if (!dateline)
    {
        return nil;
    }
    
    NSString* str = nil;
    long long lltime = [dateline longLongValue];
    if (lltime==0)
    {
        return str;
    }
    
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:lltime];
    NSDate *dateNow = [NSDate date];
    NSInteger dayApart = [dateNow daysFrom:date];
    //发布时间距离查看时间相差1天内的，显示小时数；
    //相差1天以上，7天以下的，显示天数
    if ( dayApart<7 ) {
        str = date.timeAgoSinceNow;
    }
    else
    {
        str = [date formattedDateWithFormat:@"yyyy-MM-dd"];
    }
    //7天以上的，显示具体发布日期
    
    return str;
}

//得到要显示的时间文本
+(NSString*)datetimeText:(NSString*)dateline
{
    if (!dateline)
    {
        return nil;
    }
    
    NSString* str = nil;
    long long lltime = [dateline longLongValue];
    if (lltime==0)
    {
        return str;
    }
    
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:lltime];
    str = [date formattedDateWithFormat:@"yyyy-MM-dd HH:mm"];
    
    return str;
}

+(NSString*)dateText:(NSString*)dateline
{
    if (!dateline)
    {
        return nil;
    }
    
    NSString* str = nil;
    long long lltime = [dateline longLongValue];
    if (lltime==0)
    {
        return str;
    }
    
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:lltime];
    str = [date formattedDateWithFormat:@"yyyy-MM-dd"];
    
    return str;
}

//获取时间显示字符串
+ (NSString*)dateTimeAgoText:(NSString*)datelineString
{
    if (kStringIsEmpty(datelineString))
    {
        return nil;
    }
    
    NSDate* date = [XSJTool UnixTimeToDate:datelineString.longLongValue];
    return date.timeAgoSinceNow;
}


//判断两个日期是否为同一天
+(BOOL)dateisequal:(NSString*)start_date end:(NSString*)end_date
{
    if (start_date.intValue==0 && end_date.intValue==0)
    {
        return YES;
    }
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSDate *sdate=[formatter dateFromString:start_date];
    NSDate *edate=[formatter dateFromString:end_date];
    if ([sdate isEqual:edate])
    {
        return YES;
    }
    
    return NO;
}

//判断是否为今天
+(BOOL)isTodayText:(NSString*)dateText
{
    NSString* td = [XSJTool todayText];
    return [XSJTool dateisequal:td end:dateText];
}

//获取今天的日期
+(NSString*)todayText
{
    NSDate *date = [NSDate date];
    return [date formattedDateWithFormat:@"yyyy-MM-dd"];
}

//获取今天的日期
+(NSString*)datatimeText
{
    NSDate *date = [NSDate date];
    return [date formattedDateWithFormat:@"yyyyMMddHHmmssSSS"];
}


//将图片字符串转换为URL
+(NSURL *)IconStringToUrl:(NSString*)iconString
{
    if (kStringIsEmpty(iconString))
    {
        return nil;
    }
    
    NSString* str = [NSString stringWithFormat:@"%@%@",MainUrl,iconString];
    return [NSURL URLWithString:str];
}

//得到缓存大小
+(NSUInteger)getCacheSize
{
    SDImageCache * cache = SDImageCache.sharedImageCache;
    NSUInteger size = [cache totalDiskSize];
    return size;
}

/**
 清除app缓存
 */
+(void)clearAppCache
{
    SDImageCache * cache = [SDImageCache sharedImageCache];
    [cache clearDiskOnCompletion:nil];
    [cache clearMemory];
    
    NSFileManager *fileMgr = [NSFileManager defaultManager];
    //错误信息
    NSError *error;
    
    //清空tmp目录
    NSString* path = [XSJTool GetAppTmpPath];
    [fileMgr removeItemAtPath:path error:&error];
}

//DocumentDirectory
+(NSString*)GetAppDocPath
{
    NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    return doc;
}

/**
 *  得到app的家目录下tmp目录路径，在应用退出后清空。
 *
 *  @return <#return value description#>
 */
+(NSString*)GetAppTmpPath
{
    NSString *strTmpPath = NSTemporaryDirectory();
    
    return strTmpPath;
}


//得到此view 所在的viewController
+ (UIViewController*)GetCurrentViewController:(UIView*)view
{
    UIView* next = [view superview];
    while(next)
    {
        UIResponder* nextResponder = [next nextResponder];
        if ([nextResponder isKindOfClass:[UIViewController class]])
        {
            return (UIViewController*)nextResponder;
        }
        next = next.superview;
    }
    return nil;
}

+ (UIViewController *)getCurrentVC {
    if ([[UIApplication sharedApplication].delegate.window.rootViewController isKindOfClass:UINavigationController.class] || [[UIApplication sharedApplication].delegate.window.rootViewController isKindOfClass:UITabBarController.class])
    {
        return [XSJTool getVisibleViewControllerWithRootVC:[UIApplication sharedApplication].delegate.window.rootViewController];
    }
    else
    {
        UIViewController *VC = [UIApplication sharedApplication].delegate.window.rootViewController;
        if (VC.presentedViewController)
        {
            if ([VC.presentedViewController isKindOfClass:UINavigationController.class]||
                [VC.presentedViewController isKindOfClass:UITabBarController.class])
            {
                return [XSJTool getVisibleViewControllerWithRootVC:VC.presentedViewController];
            }
            else
            {
                return VC.presentedViewController;
            }
        }
        else
        {
            return VC;
        }
    }
    
    return nil;
}

/**
 * 私有方法
 * rootVC必须是UINavigationController 或 UITabBarController 及其子类
 */
+ (UIViewController *)getVisibleViewControllerWithRootVC:(UIViewController *)rootVC
{
    if ([rootVC isKindOfClass:UINavigationController.class]) {
        UINavigationController *nav = (UINavigationController *)rootVC;
        // 如果有modal view controller并且弹起的是导航控制器，返回其topViewController
        if ([nav.visibleViewController isKindOfClass:UINavigationController.class]) {
            UINavigationController *presentdNav = (UINavigationController *)nav.visibleViewController;
            return presentdNav.visibleViewController;
        }
        else if ([nav.visibleViewController isKindOfClass:UITabBarController.class]){
            return [self getVisibleViewControllerWithRootVC:nav.visibleViewController];
        }
        // Return modal view controller if it exists. Otherwise the top view controller.
        else{
            return nav.visibleViewController;
        }
    }
    else if([rootVC isKindOfClass:UITabBarController.class]){
        UITabBarController *tabVC = (UITabBarController *)rootVC;
        UINavigationController *nav = (UINavigationController *)tabVC.selectedViewController;
        return [self getVisibleViewControllerWithRootVC:nav];
    }else{
        return rootVC;
    }
}


+(UIImage*)Color2Image:(UIColor*)color
{
    CGRect rect=CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return theImage;
}

@end
